<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
<title>门店商品管理</title>
<meta name="decorator" content="default" />
<script type="text/javascript">
	var subFlag = true;
	Dropzone.autoDiscover = false;
	//存放被删除的回选图片
	var deleteImage = "";
	var deleteDetail = "";
	var deleteService = "";
	var imageUpdateState = false;
	var detailUpdateState = false;
	var serviceUpdateState = false;
	var imageSortIndex = 0;
	var detailSortIndex = 0;
	var serviceSortIndex = 0;
	
	$(document).ready(function() {
		$("#inputForm").validate({
			onfocusout: function(element) { $(element).valid(); },  
			rules : {
				materielCode : {required : true},
				cnName : {required : true,cnNameCheck : true,rangelength:[4,30]},
				minPrice : {required : true,isPrice : true,},
				price : {required : true,isPrice : true},
				memberPrice : {required : true,isPrice : true},
			},
			messages : {
				materielCode : {required : '请选择物料编码'},
				cnName : {required : '请输入商品名称',rangelength:'请输入4-30个字符，须含汉字或字母，可带数字或标点符号'},
				minPrice : {required : '请输入保底价'},
				price : {required : '请输入售价'},
				memberPrice : {required : '请输入会员价'}
			},
			errorContainer: "#messageBox",
			errorPlacement: function(error, element) {
				$("#messageBox").text("输入有误，请先更正。");
				error.insertAfter(element);
			},
			success:function(lable){
	        	lable.remove(); 
        	},
		});
		jQuery.validator.addMethod("cnNameCheck", function(value, element) {
			return this.optional(element) || /^(?![0-9]+$)[\d\D]{4,30}$/.test(value);
		}, "请输入4-30个字符，须含汉字或字母，可带数字或标点符号");
		jQuery.validator.addMethod("isPrice", function(value, element) {
			return this.optional(element) || /^([1-9]\d{0,9}|0)([.]?|(\.\d{1,2})?)$/.test(value);
		}, "请输入正确金额");
		
		$("#btnSubmit").on("click",function(){
			//alert(imageDropzone.getAcceptedFiles());//所有接受文件
			//alert(imageDropzone.getRejectedFiles());//所有被拒绝的文件
			//alert(imageDropzone.getQueuedFiles());//所有排队的文件
			//alert(imageDropzone.getUploadingFiles());//所有上传文件
			//imageDropzone.processQueue();
			//return;
			if($("#inputForm").valid()){
				if(subFlag){
					subFlag = false;
					if(imageDropzone.getQueuedFiles().length == 0){
						imageUpdateState = true;
					}
					if(detailDropzone.getQueuedFiles().length == 0){
						detailUpdateState = true;						
					}
					if(serviceDropzone.getQueuedFiles().length == 0){
						serviceUpdateState = true;
					}
					imageDropzone.processQueue();
					detailDropzone.processQueue();
					serviceDropzone.processQueue();
					$("#deleteImage").val(deleteImage);
					$("#deleteDetail").val(deleteDetail);
					$("#deleteService").val(deleteService);
					var clock = setInterval(function(){
						if(imageUpdateState && detailUpdateState && serviceUpdateState){
							clearInterval(clock);
							$("#inputForm").submit();
						}
					}, 500); //所有图片处理完成才执行表单提交
				}else{
					loading('正在提交，请稍等...');
				}
			}
		}
		);

		//商品图片
		 var imageDropzone = new Dropzone("#imageDiv", {
	        url: "${ctx}/sys/goodsplatformmanger/saveImage",//请求地址
	        maxFiles: 5,//最大文件数
	        maxFilesize: 5,//限制文件大小,MB为单位
	        addRemoveLinks:true,//显示删除按钮
	        dictRemoveFile : "删除",//上传成功后显示的内容
	        dictCancelUpload: "", //正在上传中显示的内容
	        acceptedFiles:".jpg", //允许上传的格式
	        dictDefaultMessage:"点击此处或者拖拽文件到此处上传,最多5张图片",
	        dictInvalidInputType:"不支持的文件类型",
	        dictFileTooBig:"文件过大({{filesize}}MB). 上传文件最大支持: {{maxFilesize}}MB",
	        dictMaxFilesExceeded:"超过上传数量限制",
	        uploadMultiple:true,
	        autoProcessQueue:false,//关闭自动提交
	        parallelUploads:5,//手动触发上传时一次提交的文件数
	        init: function() {//自定义事件
	        	this.on("addedfile",function(file){//每次添加文件生成一个排序下拉框
					if(imageSortIndex <= this.options.maxFiles ){
						var name = "imageSelect";
						imageSortIndex += 1;
						$("#imageSort").append(createSelect(name+"_"+imageSortIndex,name));
						formatSelect(name);
					}
				});
	        	this.on("removedfile",function(file){//删除文件时如果删除的是回选文件则上传数上限+1.
					if(file.name.substring(0,4) == "AUTO"){
						 this.options.maxFiles = this.options.maxFiles + 1;
						 deleteImage += file.name.substring(5,file.name.length)+";";
					}
				/////
					var name = "imageSelect";
					$("#"+name+"_"+imageSortIndex).remove();
					imageSortIndex -= 1;
					formatSelect(name);
				});
	        	this.on("queuecomplete",function(){//列队上传完毕执行
					imageUpdateState = true;
				});
				var images = "${goods.image}".split(";");
				var maxLength = 0;
				if(images.length == 1 && images[0] == ""){
					maxLength = 0;
				}else{
					maxLength = images.length;
				}
				for (i = 0; i < images.length; i++) {
					if (images[i] != "") {
						var fileName ="AUTO_"+images[i].substring(images[i].lastIndexOf("/")+1,images[i].lastIndexOf("."));
						var mockFile = {
							name : fileName,
							size : 0,
							type : 'image/jpeg',
							status : Dropzone.ADDED
						};
						this.emit("addedfile", mockFile);
						this.emit("thumbnail", mockFile, "${ctx}/sys/file/getImg?filePath=" +images[i]);
						this.emit("complete", mockFile);
						this.files.push(mockFile);
					}
				}
				this.options.maxFiles = this.options.maxFiles - maxLength;
	        }
	    });
		
		
		//商品详情图片
		var detailDropzone = new Dropzone("#detailDiv", {
	        url: "${ctx}/sys/goodsplatformmanger/saveDetail",//请求地址
	        maxFiles: 5,//最大文件数
	        maxFilesize: 5,//限制文件大小,MB为单位
	        addRemoveLinks:true,//显示删除按钮
	        dictRemoveFile : "删除",//上传成功后显示的内容
	        dictCancelUpload: "", //正在上传中显示的内容
	        acceptedFiles:".jpg", //允许上传的格式
	        dictDefaultMessage:"点击此处或者拖拽文件到此处上传,最多5张图片",
	        dictInvalidInputType:"不支持的文件类型",
	        dictFileTooBig:"文件过大({{filesize}}MB). 上传文件最大支持: {{maxFilesize}}MB",
	        dictMaxFilesExceeded:"超过上传数量限制",
	        uploadMultiple:true,
	        autoProcessQueue:false,//关闭自动提交
	        parallelUploads:5,//手动触发上传时一次提交的文件数
	        init: function() {//自定义事件
	        	this.on("addedfile",function(file){//每次添加文件生成一个排序下拉框
					if(imageSortIndex <= this.options.maxFiles ){
						var name = "detailSelect";
						detailSortIndex += 1;
						$("#detailSort").append(createSelect(name+"_"+detailSortIndex,name));
						formatSelect(name);
					}
				});
	        	this.on("removedfile",function(file){//删除文件时如果删除的是回选文件则上传数上限+1.
					if(file.name.substring(0,4) == "AUTO"){
						 this.options.maxFiles = this.options.maxFiles + 1;
						 deleteDetail += file.name.substring(5,file.name.length)+";";
					}
				/////
					var name = "detailSelect";
					$("#"+name+"_"+detailSortIndex).remove();
					detailSortIndex -= 1;
					formatSelect(name);
				});
	        	this.on("queuecomplete",function(){//列队上传完毕执行
					detailUpdateState = true;
				});
				var images = "${goods.detail}".split(";");
				var maxLength = 0;
				if(images.length == 1 && images[0] == ""){
					maxLength = 0;
				}else{
					maxLength = images.length;
				}
				for (i = 0; i < images.length; i++) {
					if (images[i] != "") {
						var fileName ="AUTO_"+images[i].substring(images[i].lastIndexOf("/")+1,images[i].lastIndexOf("."));
						var mockFile = {
							name : fileName,
							size : 0,
							type : 'image/jpeg',
							status : Dropzone.ADDED
						};
						this.emit("addedfile", mockFile);
						this.emit("thumbnail", mockFile, "${ctx}/sys/file/getImg?filePath=" +images[i]);
						this.emit("complete", mockFile);
						this.files.push(mockFile);
					}
				}
				this.options.maxFiles = this.options.maxFiles - maxLength;
	        }
	    });
		
		//service图片
		var serviceDropzone = new Dropzone("#serviceDiv", {
	        url: "${ctx}/sys/goodsplatformmanger/saveService",//请求地址
	        maxFiles: 5,//最大文件数
	        maxFilesize: 5,//限制文件大小,MB为单位
	        addRemoveLinks:true,//显示删除按钮
	        dictRemoveFile : "删除",//上传成功后显示的内容
	        dictCancelUpload: "", //正在上传中显示的内容
	        acceptedFiles:".jpg", //允许上传的格式
	        dictDefaultMessage:"点击此处或者拖拽文件到此处上传,最多5张图片",
	        dictInvalidInputType:"不支持的文件类型",
	        dictFileTooBig:"文件过大({{filesize}}MB). 上传文件最大支持: {{maxFilesize}}MB",
	        dictMaxFilesExceeded:"超过上传数量限制",
	        uploadMultiple:true,
	        autoProcessQueue:false,//关闭自动提交
	        parallelUploads:5,//手动触发上传时一次提交的文件数
	        init: function() {//自定义事件
	        	this.on("addedfile",function(file){//每次添加文件生成一个排序下拉框
					if(imageSortIndex <= this.options.maxFiles ){
						var name = "serviceSelect";
						serviceSortIndex += 1;
						$("#serviceSort").append(createSelect(name+"_"+serviceSortIndex,name));
						formatSelect(name);
					}
				});
	        	this.on("removedfile",function(file){//删除文件时如果删除的是回选文件则上传数上限+1.
					if(file.name.substring(0,4) == "AUTO"){
						 this.options.maxFiles = this.options.maxFiles + 1;
						 deleteService += file.name.substring(5,file.name.length)+";";
					}
				/////
					var name = "serviceSelect";
					$("#"+name+"_"+serviceSortIndex).remove();
					serviceSortIndex -= 1;
					formatSelect(name);
				});
	        	this.on("queuecomplete",function(){//列队上传完毕执行
					serviceUpdateState = true;
				});
				var images = "${goods.service}".split(";");
				var maxLength = 0;
				if(images.length == 1 && images[0] == ""){
					maxLength = 0;
				}else{
					maxLength = images.length;
				}
				for (i = 0; i < images.length; i++) {
					if (images[i] != "") {
						var fileName ="AUTO_"+images[i].substring(images[i].lastIndexOf("/")+1,images[i].lastIndexOf("."));
						var mockFile = {
							name : fileName,
							size : 0,
							type : 'image/jpeg',
							status : Dropzone.ADDED
						};
						this.emit("addedfile", mockFile);
						this.emit("thumbnail", mockFile, "${ctx}/sys/file/getImg?filePath=" +images[i]);
						this.emit("complete", mockFile);
						this.files.push(mockFile);
					}
				}
				this.options.maxFiles = this.options.maxFiles - maxLength;
	        }
	    });
		
		var materielCode = document.getElementById("materielCode");
		//alert(materielCode[materielCode.selectedIndex].value);
		//alert($("#materielCnName").val($("#materiel_cnName_"+materielCode[materielCode.selectedIndex].value).val()));
		$("#materielCnName").val($("#materiel_cnName_"+materielCode[materielCode.selectedIndex].value).val());
		$("#materielPartsCode").val($("#materiel_partsCode_"+materielCode[materielCode.selectedIndex].value).val());
		$("#materielVenderName").val($("#materiel_venderName_"+materielCode[materielCode.selectedIndex].value).val());
	});
	
	//elect选择触发 
	function materielChange(obj){
		//$("#inputForm").valid();//解决切换验证框不消除
		$("#materielCnName").val($("#materiel_cnName_"+obj[obj.selectedIndex].value).val());
		$("#materielPartsCode").val($("#materiel_partsCode_"+obj[obj.selectedIndex].value).val());
		$("#materielVenderName").val($("#materiel_venderName_"+obj[obj.selectedIndex].value).val());
	}
	
	function selectChangeValidate(){
		$("#inputForm").valid();
	}
	
	function searchMateriel() {//点击“搜”执行的内容
		if(subFlag){
			var searchVal = $("#materielCode").data('select2').search.val();
			$("#materielCode").empty();
			$("#materielHidden").empty();
			if(searchVal==""){
				$("#materielCode").append("<option value=''>请输入物料编码</option>");
				$("#materielCode").select2().val("").trigger("change");
				return;
			}
			$("#materielCode").append("<option value=''>正在读取中...</option>");
			$("#materielCode").select2().val("").trigger("change");
			subFlag = false;
			$.ajax({
				url : "${ctx}/sys/materiel/getMaterielList",
				data : {
					"code" : searchVal
				},
				//async:false,
				dataType : "json",
				type : "post",
				success : function(data) {
					if (data.resultCode == "1") {
						$("#materielCode").empty();
						for(var i=0;i<data.list.length;i++){
							$("#materielCode").append("<option value='"+data.list[i].code+"'>"+data.list[i].code+"</option>");
							$("#materielHidden").append("<input type='hidden' id='materiel_cnName_"+data.list[i].code+"' value='"+data.list[i].cnName+"'/>");
							$("#materielHidden").append("<input type='hidden' id='materiel_partsCode_"+data.list[i].code+"' value='"+data.list[i].partsCode+"'/>");	
							$("#materielHidden").append("<input type='hidden' id='materiel_venderName_"+data.list[i].code+"' value='"+data.list[i].venderName+"'/>");
							
								 
						}
						if(data.list.length>0){
							$("#materielCode").select2().val(data.list[0].code).trigger("change");
							$("#materielCode").select2("open");
						}else{
							$("#materielCode").append("<option value=''>没有搜索到匹配项</option>");
							$("#materielCode").select2().val("").trigger("change");
						}
						
					}
					subFlag = true; 
			},
				error : function() {
					subFlag = true;
					alert("网络异常");
				}
			});
		}
	}
	
	function checkPrice(){
		$("#inputForm").validate().element("#minPrice");
		$("#inputForm").validate().element("#price");
		$("#inputForm").validate().element("#memberPrice");
	}
	
	function createSelect(id,name){
		return "<select id='"+id+"' name='"+name+"' data-old-value='' onchange='selectChange(this)' style='width:120px;margin-left:36px;'></select>";
	}
	
	function createOption(value){
		return "<option value='"+value+"'>"+value+"</option>";
	}

	function formatSelect(name){
		var selectList = $("[name="+name+"]");
		for(var i=0;i<selectList.length;i++){
			var select = selectList.get(i);
			var oldValue = select.value;
			$(select).empty();
			for(var y=0;y<selectList.length;y++){
				$(select).append("<option value='"+(y+1)+"'>"+(y+1)+"</option>");
			}
			select.options[i].selected = true;
			select.setAttribute("data-old-value",i+1);
		}
	}
	
	function selectChange(obj){
		var selectList = $("[name="+obj.name+"]");
		for(var i=0;i<selectList.length;i++){
			var select = selectList.get(i);
			if(select.value == obj.value && select != obj){
				select.options[parseInt(obj.dataset.oldValue)-1].selected = true;
				select.setAttribute("data-old-value",obj.dataset.oldValue);
			}
		}
		obj.setAttribute("data-old-value",obj.value);
	}
</script>


</head>
<body>
	<ul class="nav nav-tabs">
		<li><a href="${ctx}/sys/goodsstoremanger/">门店商品列表</a></li>
		<li class="active"><a
			href="${ctx}/sys/goodsstoremanger/form?id=${goods.id}">门店商品<shiro:hasPermission
					name="sys:goodsstoremanger:edit">${not empty goods.id?'修改':'添加'}</shiro:hasPermission>
				<shiro:lacksPermission name="sys:goodsstoremanger:edit">查看</shiro:lacksPermission></a></li>
	</ul>
	<br />
	<form:form id="inputForm" modelAttribute="goods"
		action="${ctx}/sys/goodsstoremanger/save" method="post"
		class="form-horizontal" >
		<form:hidden path="id" />
		<input type="hidden" name="deleteImage" id="deleteImage" />
		<input type="hidden" name="deleteDetail" id="deleteDetail" />
		<input type="hidden" name="deleteService" id="deleteService" />
		<sys:message content="${message}" />
		
		
		<div class="control-group">
			<label class="control-label">物料编号：</label>
			<div class="controls">
				<form:select path="materielCode" style="width:200px;" onchange="materielChange(this)" class="input-xlarge required"> 
					<c:choose>
						<c:when test="${materiel != null}">
							<form:option value="${materiel.code}">${materiel.code}</form:option>
						</c:when>
						<c:otherwise>
							<form:option value="">请输入物料编码</form:option>
						</c:otherwise>
					</c:choose>
		        </form:select>
		         <input type="button" name="" value="搜"  onclick="searchMateriel()" style="position: absolute;z-index:9999;"/>
		        <!-- 扩展select选择框无法显示更多属性的办法 -->
				<div style="display:none;" id="materielHidden">
					<c:choose>
						<c:when test="${materiel != null}">
							<input type="hidden" id="materiel_cnName_${materiel.code}" value="${materiel.cnName}"/>
					 		<input type="hidden" id="materiel_partsCode_${materiel.code}" value="${materiel.partsCode}"/>
					 		<input type="hidden" id="materiel_venderName_${materiel.code}" value="${materiel.venderName}"/>
						</c:when>
					</c:choose>
		        </div>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		
		<div class="control-group">
			<label class="control-label">物料名称：</label>
			<div class="controls">
				<input name="materielCnName" id="materielCnName" readonly="readonly" class="input-xlarge" />
			</div>
		</div>
		
		<div class="control-group">
			<label class="control-label">配件编号：</label>
			<div class="controls">
				<input name="materielPartsCode" id="materielPartsCode" readonly="readonly" class="input-xlarge" />
			</div>
		</div>
		
		<div class="control-group">
			<label class="control-label">制造商品牌：</label>
			<div class="controls">
				<input name="materielVenderName" id="materielVenderName" readonly="readonly" class="input-xlarge" />
			</div>
		</div>
		
		
		<div class="control-group">
			<label class="control-label">所属门店：</label>
			<div class="controls">
				<form:select path="storeCode" class="input-xlarge required" onchange="selectChangeValidate()">
					<option value="">所有</option>
					<form:options items="${storeList}" itemValue="code" itemLabel="cnName"/>
				</form:select>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		
		<div class="control-group">
			<label class="control-label">商品名称：</label>
			<div class="controls">
				<form:input path="cnName" htmlEscape="false" maxlength="30"
					class="input-xlarge required" />
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
	

		<div class="control-group">
			<label class="control-label">保底价格：</label>
			<div class="controls">
				<form:input path="minPrice" htmlEscape="false" maxlength="10"
					class="input-xlarge required isPrice" onkeyup="checkPrice()"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">价格：</label>
			<div class="controls">
				<form:input path="price" htmlEscape="false" maxlength="10"
					class="input-xlarge required isPrice ltMinPrice ltMemberPrice" onkeyup="checkPrice()"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">会员价：</label>
			<div class="controls">
				<form:input path="memberPrice" htmlEscape="false" maxlength="10"
					class="input-xlarge required isPrice ltMinPrice" onkeyup="checkPrice()"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		
		<div class="control-group">
			<label class="control-label">视频名称(含后缀名)：</label>
			<div class="controls">
				<form:input path="videoUrl" htmlEscape="false" maxlength="50"
					class="input-xlarge" />
			</div>
		</div>
		
		<div class="control-group">
			<label class="control-label">商品图片：</label>
			<div class="controls dropzone" id="imageDiv" style="width:50%;">
				
			</div>
			<div id="imageSort" style="width:50%;margin-left:180px;">
				
			</div>
		</div>
		
		<div class="control-group">
			<label class="control-label">商品详情：</label>
			<div class="controls dropzone" id="detailDiv" style="width:50%;">
				
			</div>
			<div id="detailSort" style="width:50%;margin-left:180px;">
				
			</div>
		</div>
		
		<div class="control-group">
			<label class="control-label">售后服务：</label>
			<div class="controls dropzone" id="serviceDiv" style="width:50%;">
				
			</div>
			<div id="serviceSort" style="width:50%;margin-left:180px;">
				
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">商品介绍：</label>
			<div class="controls">
				<form:textarea path="goodsIntroduce" id="goodsIntroduce" htmlEscape="false" rows="4" class="input-xxlarge "/>
			</div>
		</div>
		<script type="text/javascript" >
	         // Replace the <textarea id="editor1"> with a CKEditor
	         // instance, using default configuration.
	          CKEDITOR.replace( 'goodsIntroduce' ,{
            		filebrowserImageUploadUrl : "${ctx}/sys/file/uploadImage"
              });
        </script>
		<div class="form-actions">
			<shiro:hasPermission name="sys:goodsstoremanger:edit">
				<input id="btnSubmit" class="btn btn-primary" type="button"
					value="保 存" />&nbsp;</shiro:hasPermission>
			<input id="btnCancel" class="btn" type="button" value="返 回"
				onclick="history.go(-1)" />
			
		</div>
		</form:form>
</body>
</html>